<!DOCTYPE html>
<html>

<head>

    {include file="Public/header"}
    <link href="__STATIC__/layout/css/plugins/summernote/summernote.css" rel="stylesheet">
    <link href="__STATIC__/layout/css/plugins/summernote/summernote-bs3.css" rel="stylesheet">
    <link href="__STATIC__/layout/css/gyq.css" rel="stylesheet">
    <link rel="stylesheet" href="__STATIC__/layout/css/demo.css" type="text/css">
    <link rel="stylesheet" type="text/css" href="__STATIC__/layout/css/plugins/webuploader/webuploader.css">
    <link rel="stylesheet" type="text/css" href="__STATIC__/layout/css/demo/webuploader-demo.css">
    <style>
        .radio-inline input[type=radio] {
            margin-top: 4px
        }

        .note-editable {
            height: 200px
        }
    </style>
</head>

<body style="color:#333;padding:3px;" class="x_sorll">
<!-- 标题 -->
<div class="page-heade">
    <h2 class="title_color text-center">非常规促销申请</h2>
</div>
<!-- 标题 -->
<div class="row-margin-top">
    <div class="form-inline">
        <table class="table-bordered table t_table">
            <tr>
                <td style="min-width: 180px;width: 180px"><label for="">主题<span class="colorRed">*</span>：</label></td>
                <td colspan="5"><input type="text" name="title" value="{:isset($data)?$data.title:''}" id="title" class="form-control" style="min-width: 220px;width: 220px" >
                </td>
            </tr>
            <tr id="areaLatBefore" {if isset($data)}style="display: none;"{/if}>
                <td style="min-width: 180px;width: 180px"><label for="">区域维度<span class="colorRed">*</span>：</label>
                </td>
                <td colspan="5">
                    <label class="radio-inline">
                        <input type="radio" name="arealat" value="1" data-title="经销商类" {if isset($data)&&$data.arealat==1}checked{/if}>经销商类
                    </label>
                    <label class="radio-inline">
                        <input type="radio" name="arealat" data-title="网点类" value="2" {if !isset($data)||(isset($data)&&$data.arealat==2)}checked{/if}>网点类
                    </label>
                </td>
            </tr>
            <tr id="areaLatAfter"  {if !isset($data)}style="display: none;"{/if}>
                <td style="min-width: 180px;width: 180px"><label for="">区域维度：</label>
                </td>
                <td colspan="5">
                    {:isset($data)?$data.arealat_title:''}
                </td>
            </tr>
            <tr id="productBefore" {if isset($data)}style="display: none;"{/if}>
                <td style="min-width: 180px;width: 180px"><label for="">产品维度<span class="colorRed">*</span>：</label>
                </td>
                <td colspan="5">
                    <label class="radio-inline">
                        <input type="radio" name="productlat" data-title="品牌" value="1" {if isset($data)&&$data.productlat==1}checked{/if}>品牌
                    </label>
                    <label class="radio-inline">
                        <input type="radio" name="productlat" data-title="品类" value="2" {if isset($data)&&$data.productlat==2}checked{/if}>品类
                    </label>
                    <label class="radio-inline">
                        <input type="radio" name="productlat" data-title="系列" value="3" {if isset($data)&&$data.productlat==3}checked{/if}>系列
                    </label>
                    <label class="radio-inline">
                        <input type="radio" name="productlat" data-title="SKU" value="4" {if isset($data)&&$data.productlat==4}checked{/if}>SKU
                    </label>
                    <label class="radio-inline">
                        <input type="radio" name="productlat" data-title="单品" value="5" {if !isset($data)||(isset($data)&&$data.productlat==5)}checked{/if}>单品
                    </label>
                </td>
            </tr>
            <tr id="productAfter" {if !isset($data)}style="display: none;"{/if}>
                <td style="min-width: 180px;width: 180px"><label for="">产品维度：</label>
                </td>
                <td colspan="5">
                    {:isset($data)?$data.productlat_title:''}
                </td>
            </tr>
            <tr id="jxsBefore" {if isset($data)}style="display: none;"{/if}>
                <td style="min-width: 180px;width: 180px"><label for="">经销商<span class="
            colorRed">*</span>：</label></td>
                <td colspan="5">
                    <div class="col-xs-4">
                        <div class="input-group" id="jxs_input" >
                            <input type="text"   placeholder="请输入关键字或空格查询" class="form-control inputremindPeple" id="remainMan" name="jxs_id" value="{:isset($data)?$data.jxs_id:''}">
                            <div class="input-group-btn">
                                <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
                                    <span class="caret"></span>
                                </button>
                                <ul class="dropdown-menu dropdown-menu-right" role="menu">
                                </ul>
                            </div>
                        </div>
                        <div id="jxs_queding" class="selectedOnlyOne" style="display:none;" >
                            {if isset($data)}
                            <span class="inin" data-id="{$data.jxs_id}">{$data.jxs_title}</span>
                            <span class="close">×</span>
                            {else}
                            <span class="inin" ></span>
                            <span class="close">×</span>
                            {/if}
                        </div>
                    </div>
                    <div class="col-xs-2">
                        <button class="btn btn-primary btn-sm" id="select">选择</button>
                    </div>
                </td>
            </tr>
            <tr  id="jxsAfter" {if !isset($data)}style="display: none;"{/if}>
                <td style="min-width: 180px;width: 180px"><label for="">经销商：</label></td>
                <td colspan="5">
                    {:isset($data)?$data.jxs_title:''}
                </td>
            </tr>
            <tr  id="jxsbasic" {if !isset($data)}style="display: none;"{/if}>
                <td style="min-width: 180px;width: 180px"><label for="">经销商基本信息：</label></td>
                <td colspan="5">
                    {:isset($data)?$data.jxs_basic:''}
                </td>
            </tr>
            <tr>
                <td style="min-width: 180px;width: 180px"><label for="">常用模版：</label></td>
                <td><select name="" id="" class="form-control select  templ" style="min-width: 140px;width: 140px;padding:2px 12px;">
                    <option value="">请选择</option>
                    {volist name="my_t_cy" id="row"}
                    <option value="{$row.id}">{$row.title}</option>
                    {/volist}
                </select></td>
                <td style="min-width: 180px;width: 180px"><label for="">我的模版：</label></td>
                <td><select name="" id="" class="form-control select  templ" style="padding:2px 12px;">
                    <option value="">请选择</option>
                    {volist name="my_t" id="row"}
                    <option value="{$row.id}">{$row.title}</option>
                    {/volist}
                </select></td>
                <td style="min-width: 180px;width: 180px"><label for="">模版搜索：</label></td>
                <td><select name="" id="" class="form-control select templ" style="padding:2px 12px;">
                    <option value="">请选择</option>
                    {volist name="all_t" id="row"}
                    <option value="{$row.id}">{$row.title}</option>
                    {/volist}
                </select></td>
            </tr>
            <tr>
                <td colspan="6">
                    <div class="ibox float-e-margins" style="margin-bottom: 0">
                        <div class="ibox-content no-padding">

                            <div class="summernote">
                                {:isset($data)?$data.brief:''}
                            </div>

                        </div>
                    </div>
                </td>
            </tr>
            <tr>
                <td colspan="6">
                    温馨提醒：本编辑器不支持复杂表单提交，复杂表单请以附件形式提交。
                </td>
            </tr>
        </table>
        <table class="table row-margin-top table-bordered text-center bud_hei" style="margin-bottom:0;">
            <tr>
                <td colspan="25">
                    费用规划内容(金额单位：元)
                </td>
            </tr>
            <tr>
                <td colspan="25" class="text-left">
                    <button type="button" class="btn btn-info btn-sm" id="addData">添加数据</button>
                    (至少添加一条费用明细) <span class="colorRed">温馨提示：1)一个活动不要分开申请，否则会影响该活动的ROI;2)多个活动不要放在同一个申请中申请，否则会影响后续的反馈、核销。谢谢！</span>
                </td>
            </tr>
        </table>

        <table class="table table-bordered text-center bud_hei" id="mingxi">
            {if isset($str)}
            {$str}
            {else}
            <thead>
                <tr class="info">
                <td colspan="2">
                    <button class="btn btn-info btn-sm checkAll">全选</button>
                    <button class="btn btn-success btn-sm fanxuan">反选</button>
                    <button class="btn btn-danger btn-sm batchdel">批量删除</button>
                </td>
                <td>序号</td>
                <td>明细编号</td>
                <td>活动执行时间</td>
                <td>预计核销时间</td>
                <td>三级费用科目</td>
                <td>费用支付方式</td>
                <td>未税费用金额</td>
                <td>税率</td>
                <td>是否增值税(可抵扣)</td>
                <td>含税费用金额</td>
                <td>实际投入费用</td>
                <td>预计销量</td>
                <td>预计费用率</td>
                <td>2SR基准销量</td>
                <td>基准销量</td>
                <td>预计ROI</td>
                <td>备注</td>
                <td>状态</td>
                <td>提交人</td>
                <td>修改人</td>
                <td>费用计入部门</td>
                <td>费用计入方案</td>
                <td>收款方</td>
            </tr>
            </thead>
            <tbody>

            </tbody>
            <tfoot>
                <tr>
                <td style="min-width: 240px;width: 240px" colspan="2">
                    <button class="btn btn-info btn-sm checkAll">全选</button>
                    <button class="btn btn-success btn-sm fanxuan">反选</button>
                    <button class="btn btn-danger btn-sm batchdel">批量删除</button>
                </td>
                <td colspan="3" class="text-right">合计</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td class="text-right font-bold">0.00</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
                <td class="text-right font-bold">0.00</td>
                <td class="text-right font-bold">0.00</td>
                <td class="text-right font-bold">0.00</td>
                <td>-</td>
                <td class="text-right">0.00</td>
                <td class="text-right">0.00</td>
                <td colspan="8">&nbsp;</td>
            </tr>
            </tfoot>
            {/if}
        </table>

        <div class="contact-box">
            <p class="font-bold" id="zongji">
                {if isset($zongji)}{$zongji}{/if}
            </p>
        </div>
         {if isset($data)}
        {if $data.status==2}
          <div class="" style="margin:20px 10px 20px 20px;">
         <table class="table table-bordered text-left bud_hei">
            <tr class="info">
                <th class="text-left font-bold">审批意见</th>
            </tr>
            {volist name="logs" id="l"}
          <tr>
              <td>{$l.USERNAME} 审批动作：{$l.MEMO}；审批意见：{if $l.COMMENTS}{$l.COMMENTS}{else/}无{/if}(审批时间：{$l.ACTIONTIME})</td>
          </tr>
          
          {/volist}
      </table>
      </div>
      {/if}{/if}
        <div class="form-group white-bg" style="margin:20px 10px 20px 20px;">
            {if isset($attach)}
            <ul class="list-group">
                {volist name="attach" id="row"}
                <li class="list-group-item">
                    <a class="badge badge-primary removeIt" data-id="{$row.id}">移除</a>
                    <a href="{$row.path}" target="_blank">{$row.file_name}</a></li>
                {/volist}
            </ul>
            {/if}
            <div id="uploader" class="wu-example">
                <!--用来存放文件信息-->
                <div id="thelist" class="uploader-list"></div>
                <div class="btns">
                    <div id="picker">选择文件</div>
                    <button id="ctlBtn" class="btn btn-default">开始上传</button>
                </div>
                <input type="hidden" name="attach" id="attach">
                <input type="hidden" name="remove" id="remove">
            </div>
            <span>注：最多上传15个文件，每个文件小于50M,支持格式：</span><br>jpg,bnp,gif,png,jpeg,tif,raw,doc,docx,xls,xlsx,ppt,pptx,txt,pdf,rar,zip,mp4,avi,rmvb,rm,mid,3gp,AVI,3GP,,mpg,mp3,wma,wav
        </div>
        <div class="row sub_btn white-bg" style="width:100%;text-align:center;padding: 20px 0">
        {if isset($data)}
        {if $data.status==2}
                <input type="hidden" name="aid" value="{$data.id}"/>
                 <input type="hidden" id="nodeKey" name="nodeKey"/>
                  <input type="hidden" id="selectId" name="selectId"/>
                  <input type="hidden" id="selectName" name="selectName"/>
                    {volist name="btn.nextNodes" id="b"}
                      {if $b.nodeName=='结束'}
                      <input type="button" class="btn-danger btn" onclick="zuofei('{$b.nodeKey}','{$b.selectId}','{$b.selectName}')" value="点此作废"/>
                      {else/}
                      <input type="button" class="btn-info btn" onclick="baocun('{$b.nodeKey}','{$b.selectId}','{$b.selectName}')" value="保存并提交工作流"/>
                      {/if}
                    {/volist}
                {else/}
            <input type="button" class="btn btn-success save" value="保存为草稿" id="save1">
            <input type="button" class="btn btn-success save" value="保存并提交工作流" id="save2">
            <input type="button" class="btn btn-info" value="保存为模版" id="save3">
            {/if}
            {else/}
             <input type="button" class="btn btn-success save" value="保存为草稿" id="save1">
            <input type="button" class="btn btn-success save" value="保存并提交工作流" id="save2">
            <input type="button" class="btn btn-info" value="保存为模版" id="save3">
            {/if}
            <input type="button" class="btn btn-warning" value="返回" id="fanhui">
        </div>
    </div>
</div>
<!-- 全局js -->
{include file="Public/footer"}
<!-- <script src="js/plugins/metisMenu/jquery.metisMenu.js"></script> -->
<script src="__STATIC__/layout/js/plugins/slimscroll/jquery.slimscroll.min.js"></script>
<script src="__STATIC__/layout/js/plugins/summernote/summernote.min.js"></script>
<script src="__STATIC__/layout/js/plugins/summernote/summernote-zh-CN.js"></script>
<script src="__STATIC__/layout/js/plugins/suggest/bootstrap-suggest.min.js"></script>
<!--统计代码，可删除-->
<script>
 var fr={$from};
  function baocun(nodeKey,selectId,selectName){
  $("#nodeKey").val(nodeKey)
  $("#selectId").val(selectId)
  $("#selectName").val(selectName)
  var title = $('#title').val()
            if(title==''){
                swal('','请填写主题','error')
                return false
            }
            var arealat = $('[name=arealat]:checked').val()
            if(typeof arealat=='undefined'){
                swal('','请选择区域纬度','error')
                return false
            }
            var productlat = $('[name=productlat]:checked').val()
            if(typeof productlat=='undefined'){
                swal('','请选择产品纬度','error')
                return false
            }
            var jxs_id = $('[name=jxs_id]').val()
            if(jxs_id==''){
                swal('','请选择经销商','error')
                return false
            }
            var brief = $('.summernote').code()
            var list = []
            $('.upThis').each(function (i,o) {
                list.push($(o).data('id'))
            })
            if(list.length<1){
                swal('','请添加至少一条数据','error')
                return false
            }
            list = list.join(',')
            var attach = $('#attach').val()
            var remove = $('#remove').val()
            var data = {}
            data.title = title
            data.arealat = arealat
            data.productlat = productlat
            data.jxs_id = jxs_id
            data.brief = brief
            data.list = list
            data.attach = attach
            data.remove = remove
            data.ti_id = $('#ti_id').val()
            data.savetype = 3
            data.nodeKey=nodeKey
            data.selectId=selectId
            data.selectName=selectName
   $.ajax({
          cache: true,
          type: "POST",
          url:"{:url('baocunchuli')}",
          data:data,// 你的formid
          async: false,
          error: function(request) {
            alert("Connection error");
          },
          success: function(data) {
            //alert(data);
            //var res=JSON.parse(data);
                    var res1=JSON.parse(data);
                            if(res1["state"]==1){
                              swal({
                                title: "完成",
                                text: "操作已成功",
                                type: "success"
                                },function(){
                                  if(fr==1)
                                        location.href="{:url('index')}"
                                  else
                                        location.href="{:url('Workflowdb/index')}"
                                });

                          }else{
                            swal({
                            title: "错误",
                            text:  res1["msg"],
                            type: "warning"
                            });
                          }           
          }
        });
}
   function zuofei(nodeKey,selectId,selectName){
  $("#nodeKey").val(nodeKey)
  $("#selectId").val(selectId)
  $("#selectName").val(selectName)
   $.ajax({
          cache: true,
          type: "POST",
          url:"{:url('zuofeichuli')}",
          data:{aid:$("[name='aid']").val(),nodeKey:nodeKey,selectId:selectId,selectName:selectName},// 你的formid
          async: false,
          error: function(request) {
            alert("Connection error");
          },
          success: function(data) {
           //alert(data);
            //var res=JSON.parse(data);
                    var res1=JSON.parse(data);
                            if(res1["state"]==1){
                              swal({
                                title: "完成",
                                text: "操作已成功",
                                type: "success"
                                },function(){
                                   if(fr==1)
                                        location.href="{:url('index')}"
                                    else
                                        location.href="{:url('Workflowdb/index')}"
                                  //parent.layer.close(parent.layer.getFrameIndex(window.name))
                                  //
                                });

                          }else{
                            swal({
                            title: "错误",
                            text:  res1["msg"],
                            type: "warning"
                            });
                          }         
          }
        });
}
    $(document).ready(function () {

        $('.summernote').summernote({
            lang: 'zh-CN'
        });
    });
    $(document).ready(function () {

        //移除附件
        $('.removeIt').on('click',function(){
            var id = $(this).data('id')
            id = $.trim(id) //删除前后空格
            var remove = $('#remove').val()
            remove = $.trim(remove)
            var remove = ''!= remove?(remove.split(',')):[];
            if(-1==$.inArray(id,remove,0))
                remove.push(id)
            remove = remove.join(',')
            $('#remove').val(remove)

            $(this).closest('li').remove()
        })

        //添加数据
        $("#addData").click(function () {

            if ($("#title").val() == "") {
                sweetAlert("", "主题不能为空！", "error");
            } else if ($("#remainMan").val() == "") {
                sweetAlert("", "经销商不能为空！", "error");
            } else if ($(".summernote").code() == "") {
                sweetAlert("", "请填写描述信息！", "error");
            } else {
                var jxs = $('#jxs_queding .inin').html() //经销商
                var areaLat = $('[name=arealat]:checked').val() //区域纬度
                var productLat = $('[name=productlat]:checked').val() //区域纬度
                var jxs_id = $('[name=jxs_id]').val() //区域纬度
                var index = layer.open({
                    type:2,
                    title:'添加数据',
                    area:['80%','80%'],
                    maxmin:true,
                    content:'{:url("addData")}?jxs='+jxs+'&areaLat='+areaLat+'&productLat='+productLat+'&jxs_id='+jxs_id
                })
                layer.full(index)
            }
        })

        //经销商搜索自动补全
        $("#remainMan").bsSuggest({
            url: "{:url('select/myjxsjson')}",
            /*effectiveFields: ["userName", "shortAccount"],
             searchFields: [ "shortAccount"],*/
            effectiveFieldsAlias:{title: "名称"},
            ignorecase: true,
            showHeader: true,
            showBtn: false,     //不显示下拉按钮
            delayUntilKeyup: true, //获取数据的方式为 firstByUrl 时，延迟到有输入/获取到焦点时才请求数据
            idField: "id",
            keyField: "title",
            clearable: true
        }).on('onDataRequestSuccess', function (e, result) {
            console.log('onDataRequestSuccess: ', result);
        }).on('onSetSelectValue', function (e, keyword, data) {
            $('#jxs_queding').find('.inin').html(keyword.key)
            $('#jxs_queding').show()
            $('#jxs_input').hide()
            $('#jxs_input').find('input').val(keyword.id)
            //console.log('onSetSelectValue: ', keyword, data);


            $("#remainMan2").bsSuggest('destroy')
            var catbs = $("#remainMan2").bsSuggest({
                url: "{:url('select/netjson')}?keyword="+keyword.id,
                effectiveFieldsAlias:{title: "名称"},
                ignorecase: true,
                showHeader: true,
                showBtn: false,     //不显示下拉按钮
                delayUntilKeyup: true, //获取数据的方式为 firstByUrl 时，延迟到有输入/获取到焦点时才请求数据
                idField: "id",
                keyField: "title",
                clearable: true
            });

            //网点名称
            $("#remainMan2").bsSuggest('enable')
            catbs.on('onSetSelectValue', function (e, keyword, data) {
                $('#jxs_queding2').find('.inin').html(keyword.key)
                $('#jxs_queding2').show()
                $('#jxs_input2').hide()
                $('#jxs_input2').find('input').val(keyword.id)


                //产品名称
                $("#categoryName").bsSuggest('destroy')
                $("#categoryName").bsSuggest({
//                url: "{:url('select/product')}?keyword="+keyword.id,
                    url: "{:url('select/product')}",
                    effectiveFieldsAlias:{title: "名称"},
                    ignorecase: true,
                    showHeader: true,
                    showBtn: false,     //不显示下拉按钮
                    delayUntilKeyup: true, //获取数据的方式为 firstByUrl 时，延迟到有输入/获取到焦点时才请求数据
                    idField: "id",
                    keyField: "title",
                    clearable: true
                }).on('onSetSelectValue', function (e, keyword, data) {
                    $(this).val('')
                    var bool = false
                    $('#renyuan2 .ren').each(function (idx,o) {
                        if($(this).data('id') == keyword.id){
                            bool = true;
                        }
                    })
                    if(bool == false){
                        $('#renyuan2').append('<span class="ren" data-id="'+keyword.id+'">'+keyword.key+'<span class="close">×</span></span>')

                        var jxs_id = $('#remainMan').val()
                        var net_id = $('#remainMan2').val()

                        //ajax搜索产品相关信息
                        $.post('{:url("search_product_by_id")}',{id:keyword.id,jxs_id:jxs_id,net_id:net_id},function (data) {
                            $('#table1 tbody').append(data)
                        })

                    }
                });
                $("#categoryName").bsSuggest('enable')
            });
        }).on('onUnsetSelectValue', function () {
            console.log("onUnsetSelectValue");
        });

        //关闭经销商选择
        $('#jxs_queding .close').click(function () {
            $(this).closest('#jxs_queding').hide().find('.inin').html('')
            $('#jxs_input').show().find('input').val('')

        })

        //弹出经销商树
        $('#select').click(function () {
            layer.open({
                type:2,
                area:['60%','60%'],
                maxmin:true,
                content:'{:url("selectJXS")}'
            })
            return  false
        })

        /*tabel复选框操作*/
        $('body').on('click',".checkAll",function() {

            $("[name=items]:checkbox").prop("checked", true);
            if ($("[name=items]:checkbox").prop("checked") != true) {
                // console.log($(this))
                $("[name=items]:checkbox").parents("tr").css("backgroundColor", "#fff")
            } else {
                $("[name=items]:checkbox").parents("tr").css("backgroundColor", "#f8f800")

            }
            return false
        })
        $('body').on('click',"[name=items]:checkbox",function() {
            //定义一个临时变量，避免重复使用同一个选择器选择页面中的元素，提高程序效率
            // console.log(1)
            var $tmp = $("[name=items]:checkbox");
            if ($(this).prop("checked") != true) {
                // console.log($(this))
                $(this).parent().parent().css("backgroundColor", "#fff")
            } else {
                $(this).parent().parent().css("backgroundColor", "#f8f800")

            }
            //用filter()方法筛选出选中的复选框，并直接给CheckedAll赋值
          //  $("#checkAll").prop('checked', $tmp.length == $tmp.filter(':checked').length);
        })
        /*tabel复选框操作*/
        $('body').on('click',".fanxuan",function() {

            $("[name=items]:checkbox").each(function (i,o) {
                if($(this).prop('checked') == true) {
                    $(this).prop('checked',false)
                }else{
                    $(this).prop('checked',true)
                }
            })

            if ($("[name=items]:checkbox").prop("checked") != true) {
                // console.log($(this))
                $("[name=items]:checkbox").parents("tr").css("backgroundColor", "#fff")
            } else {
                $("[name=items]:checkbox").parents("tr").css("backgroundColor", "#f8f800")

            }
            return false
        })

        //删除本条
        $('body').on('click','.delThis',function () {
            if($('[name=items]').length==1){
                swal('','至少添加一条费用明细','error')
                return false
            }
            var id = $(this).data('id')
            var _this = this
            swal({
                title: "您确定删除吗",
                text: "",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确定",
                closeOnConfirm: false
            }, function (isConfirm) {
                if(isConfirm){
                    $.ajax({
                        'type':'post',
                        'url':'{:url("delItem")}',
                        'dataType':'json',
                        'data':{ids:id},
                        'success':function (data) {
                            if(data.success){
                                swal({
                                    title:data.msg,
                                    type:'error'
                                },function () {
                                    $(_this).closest('tr').remove()
                                })
                            }else
                                swal(data.msg, "", "error");
                        }
                    })
                }

            });
            return false
        })
        //修改本条
        $('body').on('click','.upThis',function () {

            var id = $(this).data('id')
            var index = layer.open({
                type:2,
                title:'修改数据',
                area:['80%','80%'],
                maxmin:true,
                content:'{:url("updateData")}?id='+id
            })
            layer.full(index)

            return false
        })

        //批量删除
        $('body').on('click','.batchdel',function () {
            if($('[name=items]:checked').length==0){
                swal('','至少选择一条费用明细','error')
                return false
            }
            if($('[name=items]:checked').length==$('[name=items]').length){
                swal('','至少添加一条费用明细','error')
                return false
            }
            var ids = []
            $('[name=items]:checked').each(function (i,o) {
                ids.push($(o).val())
            })
            ids = ids.join(',')
            swal({
                title: "您确定删除吗",
                text: "",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确定",
                closeOnConfirm: false
            }, function (isConfirm) {
                if(isConfirm){
                    $.ajax({
                        'type':'post',
                        'url':'{:url("delItem")}',
                        'dataType':'json',
                        'data':{ids:ids},
                        'success':function (data) {
                            if(data.success){
                                swal({
                                    title:data.msg,
                                    type:'error'
                                },function () {
                                    $('[name=items]:checked').closest('tr').remove()
                                })
                            }else
                                swal(data.msg, "", "error");
                        }
                    })
                }

            });
            return false
        })

        //提交
        $('.save').on('click',function () {

            var title = $('#title').val()
            if(title==''){
                swal('','请填写主题','error')
                return false
            }
            var arealat = $('[name=arealat]:checked').val()
            if(typeof arealat=='undefined'){
                swal('','请选择区域纬度','error')
                return false
            }
            var productlat = $('[name=productlat]:checked').val()
            if(typeof productlat=='undefined'){
                swal('','请选择产品纬度','error')
                return false
            }
            var jxs_id = $('[name=jxs_id]').val()
            if(jxs_id==''){
                swal('','请选择经销商','error')
                return false
            }
            var brief = $('.summernote').code()
            var list = []
            $('.upThis').each(function (i,o) {
                list.push($(o).data('id'))
            })
            if(list.length<1){
                swal('','请添加至少一条数据','error')
                return false
            }
            list = list.join(',')
            var attach = $('#attach').val()
            var remove = $('#remove').val()
            var data = {}
            data.title = title
            data.arealat = arealat
            data.productlat = productlat
            data.jxs_id = jxs_id
            data.brief = brief
            data.list = list
            data.attach = attach
            data.remove = remove
            data.ti_id = $('#ti_id').val()
            var savetype = $(this).prop('id')
            data.savetype = savetype
           // alert(savetype);
            $.post('',data,function (data) {
                if(data.success){
                    swal({
                        title: data.msg,
                        type: "success",
                    }, function () {

                        location.href = '{:url("ti_apply2/index")}'
                    })


                }else{
                    swal('',data.msg,'error')
                }

            },'json')
        })
        
        //返回
        $('#fanhui').on('click',function () {
            if(fr==1)
                                        location.href="{:url('index')}"
                                    else
                                        location.href="{:url('Workflowdb/index')}"
        })
    })
</script>

<!-- Web Uploader -->
<script type="text/javascript">
    // 添加全局站点信息
    var BASE_URL = '__STATIC__/layout/js/plugins/webuploader';
</script>
<script src="__STATIC__/layout/js/plugins/webuploader/webuploader.min.js"></script>
<script>
    // 文件上传
    jQuery(function() {
        var $ = jQuery,
            $list = $('#thelist'),
            $btn = $('#ctlBtn'),
            state = 'pending',
            uploader;

        var ids = [];
        uploader = WebUploader.create({

            // 不压缩image
            resize: false,

            // swf文件路径
            swf: BASE_URL + '/js/Uploader.swf',

            // 文件接收服务端。
            server: '{:url("upload/fileupload")}',

            // 选择文件的按钮。可选。
            // 内部根据当前运行是创建，可能是input元素，也可能是flash.
            pick: '#picker'
        });

        // 当有文件添加进来的时候
        uploader.on( 'fileQueued', function( file ) {
            $list.append( '<div id="' + file.id + '" class="item">' +
                '<h4 class="info">' + file.name + '</h4>' +
                '<p class="state">等待上传...</p>' +
                '</div>' );
        });

        // 文件上传过程中创建进度条实时显示。
        uploader.on( 'uploadProgress', function( file, percentage ) {
            var $li = $( '#'+file.id ),
                $percent = $li.find('.progress .progress-bar');

            // 避免重复创建
            if ( !$percent.length ) {
                $percent = $('<div class="progress progress-striped active">' +
                    '<div class="progress-bar" role="progressbar" style="width: 0%">' +
                    '</div>' +
                    '</div>').appendTo( $li ).find('.progress-bar');
            }

            $li.find('p.state').text('上传中');

            $percent.css( 'width', percentage * 100 + '%' );
        });

        uploader.on( 'uploadSuccess', function( file,response) {
            if(response.success)
                ids.push(response.id)
            $( '#'+file.id ).find('p.state').text(response.msg);
        });

        uploader.on( 'uploadError', function( file ) {
            $( '#'+file.id ).find('p.state').text('上传出错');
        });

        uploader.on( 'uploadComplete', function( file ) {
            $('#attach').val(ids.join(','))
            $( '#'+file.id ).find('.progress').fadeOut();
        });

        uploader.on( 'all', function( type ) {
            if ( type === 'startUpload' ) {
                state = 'uploading';
            } else if ( type === 'stopUpload' ) {
                state = 'paused';
            } else if ( type === 'uploadFinished' ) {
                state = 'done';
            }

            if ( state === 'uploading' ) {
                $btn.text('暂停上传');
            } else {
                $btn.text('开始上传');
            }
        });

        $btn.on( 'click', function() {
            if ( state === 'uploading' ) {
                uploader.stop();
            } else {
                uploader.upload();
            }
            return false
        });

        //关闭
        $('#renyuan').on('click','.ren .close',function () {
            $(this).closest('.ren').remove()
        })
        
        //保存为模板
        $('#save3').on('click',function () {
            var title = $('input[name=title]').val();
            var brief = $('.summernote').code();
            $.post('{:url("Titemplate/add")}',
                {title:title,brief:brief,ispublic:0},
                function (data) {
                    if(data.success){
                        swal({
                            title:data.msg,
                            type:'success'
                        },function () {
                            swal('保存成功', "", "error");
                        })
                    }else
                        swal(data.msg, "", "error");

                },'json')
        })
        
        //模板覆盖
        $('select.templ').on('change',function () {
            var _this = this

            var id = $(this).val()
            swal({
                title: "确定用模板替换当前内容吗",
                text: "",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确定",
                closeOnConfirm: false
            }, function (isConfirm) {
                if(isConfirm){
                    $.ajax({
                        'type':'post',
                        'url':'{:url("Titemplate/find")}?id='+id,
                        'dataType':'json',
                        'success':function (data) {
                            if(data.success){
                                $('#title').val(data.title)
                                $('.summernote').code(data.brief)
                                swal.close()
                            }else
                                swal(data.msg, "", "error");
                        }
                    })

                }

            })
        })
    });
</script>
<input type="hidden" id="ti_id" name="ti_id" value="{:request()->param('id')}">
</body>

</html>
